package name.sakanacatcher.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import name.sakanacatcher.entity.Position;
import name.sakanacatcher.service.*;
import name.sakanacatcher.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/position")
public class PositionController {
    @Autowired
    ComService comService;

    @Autowired
    RoleService roleService;

    @Autowired
    UserService userService;

    @Autowired
    ResultUtil resultUtil;

    @Autowired
    AuthService authService;

    @Autowired
    PositionService positionService;

    @Autowired
    PositionOptionTypeService positionOptionTypeService;

    @GetMapping("/search")
    public Map<String,Object> searchPosition(
            @RequestParam(required = false) String province,
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String keyword,
            @RequestParam(name = "limit") int limit,
            @RequestParam(name = "page") int page
    ) throws JsonProcessingException {
        List<Position> positions = positionService.getPositionRepository().findAll();
        // 地区过滤
        if(province != null && city != null  && province.length() > 0 && city.length() > 0)
            positions = positions.stream().filter(item -> {
                System.out.println(item.getProvince() + item.getCity());
                return item.getProvince().equals(province) && item.getCity().equals(city);
            }).collect(Collectors.toList());

        // 类型过滤
        if(type != null && type.length() > 0)
            positions = positions.stream().filter(
                item -> {
                    String[] labels = item.getLabel().split("-");
                    for (String l:labels){
                        if(type.contains(l))
                            return true;
                    }
                    return false;
                }
            ).collect(Collectors.toList());
        System.out.println(positions);
        // 关键词过滤
        if(keyword != null && keyword.length() > 0)
            positions = positions.stream().filter(
                    item -> {
                        return item.getName().contains(keyword) || item.getLabel().contains(keyword) || item.getCompany().getName().contains(keyword);
                    }
            ).collect(Collectors.toList());

        int total = positions.size();
        int totalPage = (int)Math.ceil(total / (double)limit);
        if(page <= totalPage && page >= 1){
            if(page * limit > total){
                positions = positions.subList((page - 1)*limit, total);
            }
            else {
                positions = positions.subList((page - 1)*limit,page * limit);
            }
        }
        else{
            positions = positions.subList(0,0);
        }
        System.out.println(positions);

        return resultUtil.successResult("send Success",Map.of("items",positions,"total",total));
    }

    @GetMapping("/detail")
    public Map<String,Object> searchPosition(@RequestParam int id){
        return resultUtil.successResult("send Success",Map.of("items",positionService.getPositionRepository().getById(id)));
    }

    @GetMapping("/option")
    public Map<String,Object> getPositionOption(){
        return resultUtil.successResult("send Success",Map.of("items",positionOptionTypeService.getPositionOption()));
    }

    @PostMapping("/option/delete")
    public Map<String,Object> deletePositionOption(@RequestBody Map<String,Object> data){
        return resultUtil.successResult("send Success",Map.of("items",positionOptionTypeService.deletePosition(data)));
    }

    @PostMapping("/option/add")
    public Map<String,Object> addPositionOption(@RequestBody Map<String,Object> data){
        return resultUtil.successResult("send Success",Map.of("items",positionOptionTypeService.addPosition(data)));
    }

    @PostMapping("/option/type/add")
    public Map<String,Object> addType(@RequestBody Map<String,Object> data){
        return resultUtil.successResult("send Success",Map.of("items",positionOptionTypeService.addType(data)));
    }

    @PostMapping("/option/type/delete")
    public Map<String,Object> deleteType(@RequestBody Map<String,Object> data){
        return resultUtil.successResult("send Success",Map.of("items",positionOptionTypeService.deleteType(data)));
    }

    @GetMapping("/list/cid")
    public Map<String,Object> getPositionsByCompanyId(@RequestParam int cid){
        List<Position> positions = positionService.getPositionRepository().getPositionsByCompanyId(cid);
        System.out.println(positions);
        return resultUtil.successResult("send Success",Map.of("items",positions,"total",positions.size()));
    }

    @PostMapping("/update")
    public Map<String, Object> updatePosition(@RequestBody Map<String,Object> data) {
        if(positionService.updatePosition(data)){
            return resultUtil.successResult("操作成功");
        }
        else {
            return  resultUtil.customResult(500,"未知的错误");
        }
    }

    @GetMapping("/sendResume")
    public Map<String, Object> sendResumeById(@RequestParam int id) {
        String reqUsername = SecurityContextHolder.getContext().getAuthentication().getName();
        if(!positionService.existApplicantByUsername(reqUsername,id)){
            positionService.addApplicant(reqUsername,id);
            return resultUtil.successResult("add Success");
        }

        else
            return resultUtil.customResult(405,"你已投递过简历");
    }

    @PostMapping("/delete")
    public Map<String, Object> deletePosition(@RequestBody Map<String,Object> data) {
        if(positionService.deletePosition(data)){
            return resultUtil.successResult("操作成功");
        }
        else {
            return  resultUtil.customResult(500,"未知的错误");
        }
    }

}
